# -*- coding:utf-8 -*-
# @Author   : ZGS
# @Time     : 2021/1/4 9:54
# @FileName : wy_spider.py
# 我拿青春赌明天!
import json
import time
import datetime
import requests
from tools.pymysql_ import PyMysql
from dateutil.relativedelta import relativedelta
"""
建表
CREATE TABLE `history` (
  `ds` datetime NOT NULL COMMENT '日期',
  `confirm` int(11) DEFAULT NULL COMMENT '累计确诊',
  `confirm_add` int(11) DEFAULT NULL COMMENT '当日新增确诊',
  `heal` int(11) DEFAULT NULL COMMENT '累计治愈',
  `heal_add` int(11) DEFAULT NULL COMMENT '当日新增治愈',
  `dead` int(11) DEFAULT NULL COMMENT '累计死亡',
  `dead_add` int(11) DEFAULT NULL COMMENT '当日新增死亡',
  `input` int(11) DEFAULT NULL COMMENT '境外输入',
  `input_add` int(11) DEFAULT NULL COMMENT '新增境外输入',
  `now_confirm` int(11) DEFAULT NULL COMMENT '现有确诊',
  PRIMARY KEY (`ds`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""


# 爬取历史数据
def get_wy_data():
    """
        网易数据大屏接口
    :return:
    """
    url = "https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=321948714172"

    head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"}

    res = requests.get(url, headers=head)
    res_json = json.loads(res.text)
    data = res_json['data']
    # 最后更新时间
    lastUpdateTime = data['lastUpdateTime']
    print(lastUpdateTime)

    # 全国历史数据
    chinaDayList = data['chinaDayList']
    for dt in chinaDayList:
        date = dt['date']
        print(date)
        today = dt['today']
        print(today)
        total = dt['total']
        print(total)
        print("----------------------------------------")
        # 数据打包写入数据库中
        print(date, type(date))
        # 2021的时间年份错误, 这里处理时间+一年
        if total['confirm'] > 96762:
            date = (datetime.datetime.strptime(date, '%Y-%m-%d').date() + datetime.timedelta(days=366)).strftime('%Y-%m-%d')
        dict_ = {
            "ds": date,
            "confirm": total['confirm'],    # 累计确诊
            "heal": total['heal'],          # 累计治愈
            "dead": total['dead'],          # 累计死亡
            "now_confirm": total['storeConfirm'],   # 现有确诊
            "input": total['input'],        # 境外输入
            "confirm_add": today['confirm'],    # 今日确诊
            "heal_add": today['heal'],          # 今日治愈
            "dead_add": today['dead'],          # 今日死亡
            "input_add": today['input'],        # 今日新增境外输入
        }
        print(dict_)
        mysql = PyMysql()
        mysql.insert_table(table='history', dic=dict_)
    # # 海外最后更新时间
    # overseaLastUpdateTime = data['overseaLastUpdateTime']
    # # 地区树
    # areaTree = data['areaTree']
    # for area in areaTree:
    #     print(area)
    #     break


if __name__ == '__main__':
    # https://wp.m.163.com/163/page/news/virus_report/index.html?_nw_=1&_anw_=1
    get_wy_data()
